package com.zj.leetcode.easy.tree;

/**
 * @program: algorithm
 * @description: 根据二叉树创建字符串
 * 606 construct-string-from-binary-tree
 * @author: Zhang Bo
 * @create: 2022-06-29 10:20:05
 **/
public class ConstructStringFromBinaryTree {
    public static void main(String[] args) {
        Solution solution = new ConstructStringFromBinaryTree().new Solution();
    }
    //leetcode submit region begin(Prohibit modification and deletion)

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    class Solution {
        StringBuilder sb = new StringBuilder();

        public String tree2str(TreeNode root) {
            if (root == null) {
                return sb.toString();
            }
            this.dfs(root);
            return sb.toString();
        }

        private void dfs(TreeNode node) {
            if(node != null){
                sb.append(node.val);
                if (node.left != null || node.right != null) {
                    sb.append("(");
                    this.dfs(node.left);
                    sb.append(")");

                    if (node.right != null) {
                        sb.append("(");
                        this.dfs(node.right);
                        sb.append(")");
                    }
                }

            }

        }
    }
//leetcode submit region end(Prohibit modification and deletion)

}
